<?php
/* This file is part of LlamaSlayers Ajax Chat
 *
 * The source code is released under the GNU GPL free software license, version 3.
 * Updates can be found at http://llamaslayers-ajax-chat.googlecode.com/
 */

require_once dirname( __FILE__ ) . '/config.php';

function superhash_rotate( $password, $by ) {
	if ( !$by )
		return $password;
	$password = str_split( $password );
	foreach ( $password as &$p ) {
		$p = chr( ( ord( $p ) + $by ) % 255 );
	}
	return implode( '', $password );
}

function superhash_make_key() {
	$secretkey = '';
	for ( $i = 0; $i < 256; $i++ ) {
		$secretkey .= chr( mt_rand( 32, 126 ) );
	}
	define( 'SECRET_KEY', $secretkey );

	$secretkey = addslashes( $secretkey );

	$config = file_get_contents( dirname( __FILE__ ) . '/config.php' );
	$config = str_replace( '?' . '>', "\ndefine( 'SECRET_KEY', '" . $secretkey . "' );\n\n?" . '>', $config );
	file_put_contents( dirname( __FILE__ ) . '/config.php', $config );
}

function superhash( $password, $check = false ) {
	if ( !defined( 'SECRET_KEY' ) ) {
		superhash_make_key();
	}

	if ( $check === false ) {
		$salt1 = '';
		$salt2 = '';
		for ( $i = 0; $i < 16; $i++ ) {
			$salt1 .= chr( mt_rand( 0, 255 ) );
		}
		for ( $i = 0; $i < 16; $i++ ) {
			$salt2 .= chr(mt_rand(0, 255));
		}
	} elseif ( strlen( $check ) == 48 ) {
		$salt1 = substr( $check, 0, 16 );
		$salt2 = substr( $check, 32 );
	} elseif ( strlen( $check = base64_decode( $check ) ) == 48 ) {
		$salt1 = substr( $check, 0, 16 );
		$salt2 = substr( $check, 32 );
	} else {
		return false;
	}
	$password = superhash_rotate( $password, ord( sha1( $salt1 . $salt2, true ) ) );
	return $salt1 . md5( strrev( gzdeflate( $salt1 . implode( SECRET_KEY, str_split( $password, strlen( $password ) / 2 + 1 ) ) . $salt2, 9 ) ), true ) . $salt2;
}

?>